"use client"

import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import { Plus, Search, Settings, Plug, CheckCircle2, XCircle, Trash2 } from "lucide-react"
import Link from "next/link"
import { useState, useEffect } from "react"
import { useToast } from "@/hooks/use-toast"
import { mockData, type MCP } from "@/lib/mock-data"

const availableMCPs = [
  {
    id: "market-1",
    name: "Notion MCP",
    description: "连接到 Notion 工作区，管理页面和数据库",
    category: "生产力",
    downloads: "12.5k",
    rating: 4.8,
  },
  {
    id: "market-2",
    name: "Jira MCP",
    description: "管理 Jira 项目、Issues 和工作流",
    category: "项目管理",
    downloads: "8.3k",
    rating: 4.6,
  },
  {
    id: "market-3",
    name: "PostgreSQL MCP",
    description: "连接到 PostgreSQL 数据库执行查询",
    category: "数据库",
    downloads: "15.2k",
    rating: 4.9,
  },
]

export default function MCPPage() {
  const { toast } = useToast()
  const [connectedMCPs, setConnectedMCPs] = useState<MCP[]>([])
  const [searchQuery, setSearchQuery] = useState("")

  useEffect(() => {
    setConnectedMCPs(mockData.getMCPs())
  }, [])

  const filteredMarketMCPs = availableMCPs.filter(
    (mcp) =>
      mcp.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      mcp.description.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const handleInstallMCP = (marketMCP: (typeof availableMCPs)[0]) => {
    const newMCP = mockData.addMCP({
      name: marketMCP.name,
      description: marketMCP.description,
      status: "connected",
      version: "1.0.0",
      lastSync: "刚刚",
      endpoints: 5,
      category: marketMCP.category,
    })

    setConnectedMCPs([...connectedMCPs, newMCP])

    toast({
      title: "MCP 已安装",
      description: `${marketMCP.name} 已成功安装并连接`,
    })
  }

  const handleDeleteMCP = (mcp: MCP) => {
    mockData.deleteMCP(mcp.id)
    setConnectedMCPs(connectedMCPs.filter((m) => m.id !== mcp.id))

    toast({
      title: "MCP 已删除",
      description: `${mcp.name} 已从系统中移除`,
    })
  }

  const handleToggleStatus = (mcp: MCP) => {
    const newStatus = mcp.status === "connected" ? "disconnected" : "connected"
    mockData.updateMCP(mcp.id, { status: newStatus })
    setConnectedMCPs(connectedMCPs.map((m) => (m.id === mcp.id ? { ...m, status: newStatus } : m)))

    toast({
      title: "状态已更新",
      description: `${mcp.name} 已${newStatus === "connected" ? "连接" : "断开"}`,
    })
  }

  return (
    <AuthGuard>
      <DashboardLayout>
        <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold tracking-tight">MCP 管理</h1>
              <p className="text-muted-foreground mt-2">管理模型上下文协议连接</p>
            </div>
            <Link href="/dashboard/mcp/create">
              <Button>
                <Plus className="mr-2 h-4 w-4" />
                创建自定义 MCP
              </Button>
            </Link>
          </div>

          {/* Tabs */}
          <Tabs defaultValue="connected" className="space-y-4">
            <TabsList>
              <TabsTrigger value="connected">已连接 ({connectedMCPs.length})</TabsTrigger>
              <TabsTrigger value="marketplace">MCP 市场</TabsTrigger>
            </TabsList>

            {/* Connected MCPs */}
            <TabsContent value="connected" className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {connectedMCPs.map((mcp) => (
                  <Card key={mcp.id} className="hover:shadow-md transition-shadow">
                    <CardHeader>
                      <div className="flex items-start justify-between">
                        <div className="flex items-start gap-3 flex-1">
                          <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                            <Plug className="h-5 w-5 text-primary" />
                          </div>
                          <div className="space-y-1 flex-1 min-w-0">
                            <CardTitle className="text-lg truncate">{mcp.name}</CardTitle>
                            <CardDescription className="line-clamp-2">{mcp.description}</CardDescription>
                          </div>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center gap-2">
                        <Badge variant="outline">v{mcp.version}</Badge>
                        {mcp.status === "connected" ? (
                          <Badge variant="default" className="gap-1">
                            <CheckCircle2 className="h-3 w-3" />
                            已连接
                          </Badge>
                        ) : (
                          <Badge variant="destructive" className="gap-1">
                            <XCircle className="h-3 w-3" />
                            {mcp.status === "error" ? "错误" : "已断开"}
                          </Badge>
                        )}
                      </div>
                      <div className="space-y-1 text-sm">
                        <div className="flex justify-between text-muted-foreground">
                          <span>端点数量</span>
                          <span className="font-medium text-foreground">{mcp.endpoints}</span>
                        </div>
                        <div className="flex justify-between text-muted-foreground">
                          <span>最后同步</span>
                          <span className="font-medium text-foreground">{mcp.lastSync}</span>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          className="flex-1 bg-transparent"
                          onClick={() => handleToggleStatus(mcp)}
                        >
                          <Settings className="mr-2 h-4 w-4" />
                          {mcp.status === "connected" ? "断开" : "连接"}
                        </Button>
                        <Button variant="outline" size="icon" onClick={() => handleDeleteMCP(mcp)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </TabsContent>

            {/* MCP Marketplace */}
            <TabsContent value="marketplace" className="space-y-4">
              <div className="flex items-center gap-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索 MCP..."
                    className="pl-9"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                  />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {filteredMarketMCPs.map((mcp) => (
                  <Card key={mcp.id} className="hover:shadow-md transition-shadow">
                    <CardHeader>
                      <div className="flex items-start gap-3">
                        <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                          <Plug className="h-5 w-5 text-primary" />
                        </div>
                        <div className="space-y-1 flex-1 min-w-0">
                          <CardTitle className="text-lg truncate">{mcp.name}</CardTitle>
                          <CardDescription className="line-clamp-2">{mcp.description}</CardDescription>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center gap-2">
                        <Badge variant="secondary">{mcp.category}</Badge>
                      </div>
                      <div className="flex items-center justify-between text-sm text-muted-foreground">
                        <span>{mcp.downloads} 下载</span>
                        <span className="flex items-center gap-1">
                          <span className="text-yellow-500">★</span>
                          {mcp.rating}
                        </span>
                      </div>
                      <Button className="w-full" onClick={() => handleInstallMCP(mcp)}>
                        <Plus className="mr-2 h-4 w-4" />
                        安装
                      </Button>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </DashboardLayout>
    </AuthGuard>
  )
}
